package com.cqdev.washer.infra.service;

import com.alibaba.druid.pool.DruidDataSource;
import com.cqdev.washer.biz.model.DbConfigBO;
import com.cqdev.washer.infra.util.Caches;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;

/**
 * @author yunfei.li
 *         类描述: TODO
 *         日期： 2018/6/22
 */
@Service
public class JdbcTemplateService {

    private static Caches.CacheHelper jdbcTemplateCacheHelper = Caches.from(60 * 60, 10);

    private DataSource buildDataSource(String url, String driverClassName, String username, String password) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    public JdbcTemplate jdbcTemplate(DbConfigBO dbConfig) {
        if (dbConfig == null) {
            throw new RuntimeException("connection db config error.");
        }

        JdbcTemplate jdbcTemplate = jdbcTemplateCacheHelper.get(dbConfig.getId().toString());
        if (jdbcTemplate == null) {
            DataSource dataSource = buildDataSource(dbConfig.getUrl(), dbConfig.getDbDriverType().getDriverClassName(), dbConfig.getUsername(), dbConfig.getPassword());
            jdbcTemplate = new JdbcTemplate(dataSource);
            jdbcTemplateCacheHelper.put(dbConfig.getId().toString(), jdbcTemplate);
        }

        return jdbcTemplate;
    }


}
